//
//  KLPhotoSelectorViewController.swift
//  BCWeiBo
//
//  Created by bcmac3 on 16/4/7.
//  Copyright © 2016年 KellenYangs. All rights reserved.
//

import UIKit

private let KLPhotoSelectorReuseIdentifier = "KLPhotoSelectorReuseIdentifier"

class KLPhotoSelectorViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareCollectionView()
    }

    private func prepareCollectionView() {
        // 1.添加控件
        view.addSubview(collectionView)
        
        // 2.设置 layout
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        // 3.设置collectionView
        collectionView.backgroundColor = UIColor.lightGrayColor()
        collectionView.registerClass(KLPhotoSelectorViewCell.self, forCellWithReuseIdentifier: KLPhotoSelectorReuseIdentifier)
        collectionView.dataSource = self
        
        // 4.设置布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        var cons = [NSLayoutConstraint]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView])
        view.addConstraints(cons)
        
    }
    
    // MARK: 懒加载
    private lazy var layout = UICollectionViewFlowLayout()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    /// 图像数组
    lazy var photos = [UIImage]()
    
}

extension KLPhotoSelectorViewController: UICollectionViewDataSource
{
    // MARK: 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return photos.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(KLPhotoSelectorReuseIdentifier, forIndexPath: indexPath) as! KLPhotoSelectorViewCell
        // 设置代理
        cell.photoDelegate = self
        // 设置图片，比数据源多一个，让最后一个作为添加照片的按钮
        cell.image = indexPath.item < photos.count ? photos[indexPath.item] : nil
        cell.backgroundColor = UIColor.redColor()
        
        return cell
    }
    
}

extension KLPhotoSelectorViewController: KLPhotoSelectorViewCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    // MAKR: - PhotoSelectorViewController
    ///  要选择照片
    func photoSelectorSelectPhoto(cell: KLPhotoSelectorViewCell)
    {
        // UIImagePickerController 专门用来选择照片的
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            
            return
        }
        
        let vc = UIImagePickerController()
        vc.delegate = self
        
        // 允许编辑 － 如果要上传头像，记得把这个属性打开
        // 能够建立一个正方形的图像，方便后续的头像处理
        //        vc.allowsEditing = true
        
        presentViewController(vc, animated: true, completion: nil)
        
    }
    ///  要删除照片
    func photoSelectorDeletePhoto(cell: KLPhotoSelectorViewCell)
    {
        // indexPath
        let indexPath = collectionView.indexPathForCell(cell)
        
        // 删除照片
        photos.removeAtIndex(indexPath!.item)
        
        // 更新数据
        collectionView.reloadData()
    }
    
    // MAKR: - UIImagePickerControllerDelegate/UINavigationControllerDelegate
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 提示：所有关于相册的处理，都要处理内存！
        // 将图像添加到数组
        photos.append(image.scaleImageToWidth(300))
        collectionView.reloadData()
        
        // 一旦实现了协议方法，就需要我们自己关闭
        dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc
protocol KLPhotoSelectorViewCellDelegate: NSObjectProtocol {
    ///  要选择照片
    optional func photoSelectorSelectPhoto(cell: KLPhotoSelectorViewCell)
    ///  要删除照片
    optional func photoSelectorDeletePhoto(cell: KLPhotoSelectorViewCell)
}

/// 照片选择 cell
class KLPhotoSelectorViewCell: UICollectionViewCell {
    
    // unwrapping an Optional value
    // 不能解包可选项 -> 将 nil 使用了惊叹号
    var image: UIImage? {
        didSet {
            
            if image != nil {
                photoButton.setImage(image, forState: UIControlState.Normal)
            } else {
                photoButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                photoButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
            }
            
            removeButton.hidden = (image == nil)
        }
    }
    
    // 定义代理
    weak var photoDelegate: KLPhotoSelectorViewCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        
        // 1.添加控制
        contentView.addSubview(photoButton)
        contentView.addSubview(removeButton)
        photoButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        // 2.设置布局
        photoButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        var cons = [NSLayoutConstraint]()
        // 背景
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[photoButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["photoButton": photoButton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[photoButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["photoButton": photoButton])
        
        // 删除按钮
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[removeButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton":removeButton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[removeButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton":removeButton])
        
        contentView.addConstraints(cons)
        
        // 设置监听方法
        photoButton.addTarget(self, action: "selectPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "deletePhoto", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    func selectPhoto()
    {
        if image == nil{
            
            photoDelegate?.photoSelectorSelectPhoto!(self)
        }
    }
    
    func deletePhoto(){
        photoDelegate?.photoSelectorDeletePhoto!(self)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载
    private lazy var photoButton: UIButton = KLPhotoSelectorViewCell.createButton("compose_pic_add")
    private lazy var removeButton: UIButton = KLPhotoSelectorViewCell.createButton("compose_photo_close")
    
    /// 创建按钮
    class func createButton(imageName: String) -> UIButton {
        let button = UIButton()
        
        button.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        button.setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
        
        return button
    }
}

